package com.rou.im.boot.starter.server.netty;

import com.rou.im.boot.starter.server.netty.config.NettyConfigProperties;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.DefaultThreadFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.StringUtils;

import java.io.Closeable;
import java.util.concurrent.ThreadFactory;

/**
 * <p></p>
 *
 * @author GaoShuangWen
 * @since 2020-05-04 0:06
 */

public class EventLoopGroupManager implements InitializingBean {

    private EventLoopGroup bossGroup;

    private EventLoopGroup workerGroup;

    private final NettyConfigProperties config;

    public EventLoopGroupManager(NettyConfigProperties config) {
        this.config = config;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        NettyConfigProperties.LoopGroup loopGroup = config.getLoopGroup();
        bossGroup = new NioEventLoopGroup(config.getLoopGroup().getBossCount(),
                StringUtils.isEmpty(loopGroup.getBossThreadName()) ? new DefaultThreadFactory(NioEventLoopGroup.class)
                        : new DefaultThreadFactory(loopGroup.getBossThreadName()));
        workerGroup = new NioEventLoopGroup(config.getLoopGroup().getWorkerCount(),
                StringUtils.isEmpty(loopGroup.getWorkerThreadName()) ? new DefaultThreadFactory(NioEventLoopGroup.class)
                        : new DefaultThreadFactory(loopGroup.getWorkerThreadName()));
    }


    public void close() {
        bossGroup.shutdownGracefully();
        workerGroup.shutdownGracefully();
    }

    public EventLoopGroup getBossGroup() {
        return bossGroup;
    }

    public EventLoopGroupManager setBossGroup(EventLoopGroup bossGroup) {
        this.bossGroup = bossGroup;
        return this;
    }

    public EventLoopGroup getWorkerGroup() {
        return workerGroup;
    }

    public EventLoopGroupManager setWorkerGroup(EventLoopGroup workerGroup) {
        this.workerGroup = workerGroup;
        return this;
    }


}
